import Vue from 'vue'
import VueRouter from 'vue-router'
import Home from '../views/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path: '/',
    name: 'Home',
    component: Home,
    children: []
  },{
    path: '/register',
    name: "register",
    meta: {
      isNotNeed: false
    },
    component: () => import('../views/user/Register')
  },
  {
    path: '/login',
    name: 'login',
    meta: {
      isNotNeed: false
    },
    component: () => import('../views/user/Login')
  }
]

// push方法改写 防止同路由跳转报错
const routerPush = VueRouter.prototype.push
VueRouter.prototype.push = function push(location) {
  if(typeof(location)=="string"){
    var Separator = "&";
    if(location.indexOf('?')==-1) { Separator='?'; }
    location = location + Separator + "random=" + Math.random();
  }
  return routerPush.call(this, location).catch(error=> error)
}

const router = new VueRouter({
  routes
})

// 全局前置守卫 检测页面进入是否需要token
router.beforeEach((to, from, next) => {
  var data = JSON.parse(localStorage.getItem('vuex'))
  if(to.matched.some(item => item.isNotNeed)) {
    if(!data || !data.token) {
      next('/login')
    } else {
      next()
    }
  } else {
    next()
  }
  
})
export default router
